package cn.itcast.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import cn.itcast.utils.MD5Utils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class userServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(readOnly = true)
    public List<String> findRoleByUsername(String username) {
        return userDao.findRoleByUsername(username);
    }

    @Override
    @Transactional(readOnly = true)
    public List<String> findPermissionByUsername(String username) {
        return userDao.findPermissionByUsername(username);
    }

    @Override
    @Transactional(readOnly = true)
    public User findUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult findByPage(Integer currentPage, Integer pageSize, String queryString) {
        //开启分页查询
        PageHelper.startPage(currentPage, pageSize);
        //根据条件分页查询检查项信息
        Page<User> page = userDao.selectByCondition(queryString);
        //构建分页数据返回
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Boolean save(List<Integer> roleIds, User user) {
        if (ObjectUtil.isEmpty(user)) {
            return false;
        }
        String password = MD5Utils.md5(user.getPassword());
        user.setPassword(password);
        Integer integer = userDao.save(user);
        user = findUserByUsername(user.getUsername());
        int count = 1;
        if (CollUtil.isNotEmpty(roleIds)) {
            for (Integer roleId : roleIds) {
                integer += userDao.saveUserAndRole(user.getId(), roleId);
            }
            count += roleIds.size();
        }
        return integer == count;
    }

    @Override
    public Boolean delete(Integer id) {
        userDao.deleteUserAndRole(id);
        return userDao.delete(id) > 0;
    }

    @Override
    public Boolean edit(List<Integer> roleIds, User user) {
        Boolean flag1 = delete(user.getId());
        Boolean flag2 = save(roleIds, user);
        return flag1 && flag2;
    }

    @Override
    @Transactional(readOnly = true)
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<User> findAll() {
        return null;
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userDao.findRoleIdsByUserId(userId);
    }
}
